package com.one.service.impl;

import com.one.mapper.CleanRcordMapper;
import com.one.mapper.LandMapper;
import com.one.mapper.StoreMapper;
import com.one.pojo.CleanRecord;
import com.one.pojo.Land;
import com.one.pojo.OneUser;
import com.one.pojo.Store;
import com.one.service.StoreService;
import com.one.util.StringUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.List;

/**
 * @Description
 * @Author semstouch
 * @Date 2017/4/8
 **/
@Service
public class StoreServiceImpl implements StoreService{
    @Resource
    private StoreMapper storeMapper;
    @Resource
    private LandMapper landMapper;
    @Resource
    private CleanRcordMapper cleanRcordMapper;

    @Override
    public boolean update(Store store) {
        return storeMapper.updateByPrimaryKeySelective(store)>0?true:false;
    }

    @Override
    public Store findByUserId(String userId) {
        return storeMapper.findByUserId(userId);
    }

    @Override
    public BigDecimal cleanFriendFarm(OneUser oneUser, OneUser friendUser) {
        Store store = storeMapper.findByUserId(oneUser.getUserId());
        Store friendStore =storeMapper.findByUserId(friendUser.getUserId());
        List<Land>  landList = landMapper.findByChickenfarmIdAndCollectFlag(friendUser.getFarmId(), "0");
        if(landList==null){
            return null;
        }
        int landSize=landList.size();
        BigDecimal totalCleanNum=new BigDecimal(0);
        for(int i=0;i<landSize;i++){
            Land land =landList.get(i);
            BigDecimal eggsNum=land.getEggsIncome();
            BigDecimal cleanNum =eggsNum.multiply(new BigDecimal(0.1));
            totalCleanNum=totalCleanNum.add(cleanNum);
            store.setEggsNum(store.getEggsNum().add(cleanNum));
            friendStore.setEggsNum(friendStore.getEggsNum().add(eggsNum));
            landList.get(i).setCollectFlag("1");
            landMapper.updateByPrimaryKeySelective(land);
            storeMapper.updateByPrimaryKeySelective(store);
            storeMapper.updateByPrimaryKeySelective(friendStore);
        }

        CleanRecord cleanRecord = new CleanRecord();
        cleanRecord.setCleanId(oneUser.getUserId());
        cleanRecord.setFriendId(friendUser.getUserId());
        cleanRecord.setFriendLoginName(friendUser.getLoginName());
        cleanRecord.setCleanNum(totalCleanNum);
        cleanRecord.setDaily(StringUtils.getStringToday());
        cleanRcordMapper.insertSelective(cleanRecord);

        return totalCleanNum;
    }
}
